package net.fornwall.eclipsecoder.archive;

import net.fornwall.eclipsecoder.preferences.EclipseCoderPlugin;
import net.fornwall.eclipsecoder.util.Utilities;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;

/**
 * A job to retrieve a specified submission to a TopCoder problem from the
 * online archive and display it in an editor.
 */
public class SubmissionFetcherJob extends Job {

	Submission submission;

	private int roundId;

	private int problemId;

	public SubmissionFetcherJob(Submission submission, int roundId,
			int problemId) {
		super("Retrieving submission");
		this.submission = submission;
		this.roundId = roundId;
		this.problemId = problemId;
	}

	@Override
	protected IStatus run(IProgressMonitor monitor) {
		monitor.beginTask("Retrieving submission", 100);
		try {
			monitor.subTask("Logging in");
			ProblemScraper scraper = new ProblemScraper(EclipseCoderPlugin
					.tcUserName(), EclipseCoderPlugin.tcPassword());
			if (monitor.isCanceled()) {
				return Status.CANCEL_STATUS;
			}
			monitor.worked(20);
			final String submissionString = scraper.getSubmission(submission
					.getCoderId(), roundId, problemId, monitor);
			if (submissionString == null) {
				return new Status(IStatus.ERROR, EclipseCoderPlugin.PLUGIN_ID,
						IStatus.OK,
						"The submission to this problem is not available.",
						null);
			}

			if (monitor.isCanceled()) {
				return Status.CANCEL_STATUS;
			}
			monitor.subTask("Opening editor");
			Utilities.runInDisplayThread(new Runnable() {

				public void run() {
					String fileExtension = "txt";
					if (submission.getLanguage().equals("Java")) {
						fileExtension = "java";
					} else if (submission.getLanguage().equals("C++")) {
						fileExtension = "cpp";
					} else if (submission.getLanguage().equals("C#")) {
						fileExtension = "cs";
					} else if (submission.getLanguage().equals("VB")) {
						fileExtension = "vb";
					}

					EditorOpener.openEditor(submissionString, submission
							.getCoderHandle()
							+ "'s submission", submission.getCoderHandle()
							+ "'s submission to the problem", fileExtension);
				}

			});
			return Status.OK_STATUS;
		} catch (Exception e1) {
			return new Status(IStatus.WARNING, EclipseCoderPlugin.PLUGIN_ID,
					IStatus.OK, "Failed retrieving submission: "
							+ e1.getMessage(), e1);
		}
	}

}
